<?php
namespace Act\Os;
use Act\Os\Backend;
use Lib\Page;
use Lib\Common;
class Regions extends Backend{
	private $view_types = ['province'=>'市','city'=>'县','district'=>''];
	public function doGet(){
		$query = [
			'province'=>get('province','','trim,htmlspecialchars'),
			'city'=>get('city','','trim,htmlspecialchars'),
			'district'=>get('district','','trim,htmlspecialchars'),
		];
		$keys = array_keys($query);
		$values = array_values($query);
		$count = count($values)-1;
		$type = 'province';
		$name = '';

		$name = '';
		$fid = get('fid',0,'absint');
		while($count>=0){
			if(($name = $values[$count]) && ($type=$keys[$count])){
				break;
			}
			$count--;
		}
		$mod = model('#'.ucwords($type));
		$count = $mod->searchCount($name,$fid);
		$page = new Page($count,self::PAGE_SIZE);
		$regions = $mod->search($name,$fid,$page->offset,$page->size);
		$_GET = $query;
		$this->display('index.php',array(
			'regions'=>$regions,
			'page_html'=>$page->show(),
			'view_type'=>$this->view_types[$type],
			'type'=>$type,
			'admin_action_confirm'=>Common::renderJsConfirm('icon-remove'),
			));
	}

	public function doDelete(){
		$id = get('id',0,'absint');
		$type = get('type','','trim,htmlspecialchars');
		$u_type = ucwords($type);
		$this->checkParam($type);
		if(!in_array($type,array_keys($this->view_types))){
			return $this->error('非法操作',referer());
		}
		$child_types = ['province'=>'city','city'=>'district','district'=>''];
		$child_type = $child_types[$type];

		$mod = model('#'.$u_type);

		if(!empty($child_type)){
			$method = 'get'.$u_type.'ById';
			$region = $mod->$method($id);
			$c_mod = model('#'.ucwords($child_type));
			if($c_mod->searchCount('',$region['sn'])){
				return $this->error('存在下级，不能删除',referer());
			}

		}

		$ret = $mod->delById($id);
		if($ret){
			return $this->success('删除地区成功',referer());
		}else{
			return $this->error($mod->getError(),referer());
		}
	}
}